<!--
Copyright 2013 The Polymer Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-->
<polymer-element name="tk-publisher" attributes="sourceElement">
  <script>
  (function() {
    Polymer('tk-publisher', {
      sourceElement: null,
      publishElement: function(source) {
        if (source) {
          this.register(source);
          this.makeMeta();
        }
      },
      register: function(source) {
        if (source) {
          var elt = elementFromHTML(source, 'polymer-element');
          var script = source.match(new RegExp('<script>([\\s\\S]*)</scr'
              + 'ipt>', 'm'));
          if (script) {
            var s = document.createElement('script');
            s.textContent = script[1];
            document.head.appendChild(s);
            document.head.removeChild(s);
          }
          document.head.appendChild(elt);
          CustomElements.takeRecords();
          document.head.removeChild(elt);
          this.elementName = elt.getAttribute('name');
          return elt;
        }
      },
      makeMeta: function() {
        var meta = document.createElement('tk-meta');
        meta.cancelUnbindAll();
        var existingMeta = meta.byId(this.elementName);
        if (existingMeta) {
          existingMeta.unregister(existingMeta, existingMeta.id);
        }
        meta.shouldPrepend = true;
        meta.id = this.elementName;
        meta.label = this.elementName;
        meta.isContainer = true;
        var template = document.createElement('template');
        template.innerHTML = this.makeArchetypeHTML();
        meta.appendChild(template);
      },
      makeArchetypeHTML: function(name) {
        var size = this.calcSize();
        return '<' + this.elementName + ' style="display: block; width: ' +
            size.width + 'px; ' + 'height: ' + size.height + 'px;">' +
            '</' + this.elementName + '>'
      },
      calcSize: function() {
        this.sourceElement.style.right = 
            this.sourceElement.style.bottom = 'auto';
        var size = {
          width: this.sourceElement.scrollWidth,
          height: this.sourceElement.scrollHeight
        };
        this.sourceElement.style.right = 
            this.sourceElement.style.bottom = null;
        return size;
      }
    });

    function elementFromHTML(html, selector) {
      var d = document.createElement('div');
      d.innerHTML = html;
      return d.querySelector(selector);
    }
  })();
  </script>  
</polymer-element>